package com.coai.user.controller

import com.coai.common.dto.ApiResponse
import com.coai.user.dto.*
import com.coai.user.service.UserService
import jakarta.validation.Valid
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/users")
class UserController(
    private val userService: UserService
) {
    
    @PostMapping("/register")
    fun register(@Valid @RequestBody request: RegisterRequest): ApiResponse<UserDto> {
        val user = userService.register(request)
        return ApiResponse.success(user, "注册成功")
    }
    
    @PostMapping("/login")
    fun login(@Valid @RequestBody request: LoginRequest): ApiResponse<LoginResponse> {
        val response = userService.login(request)
        return ApiResponse.success(response, "登录成功")
    }
    
    @GetMapping("/me")
    fun getCurrentUser(@AuthenticationPrincipal userId: String): ApiResponse<UserDto> {
        val user = userService.getUserById(userId)
        return ApiResponse.success(user)
    }
    
    @GetMapping("/{userId}")
    fun getUserById(@PathVariable userId: String): ApiResponse<UserDto> {
        val user = userService.getUserById(userId)
        return ApiResponse.success(user)
    }
    
    @GetMapping("/username/{username}")
    fun getUserByUsername(@PathVariable username: String): ApiResponse<UserDto> {
        val user = userService.getUserByUsername(username)
        return ApiResponse.success(user)
    }
    
    @PutMapping("/me")
    fun updateCurrentUser(
        @AuthenticationPrincipal userId: String,
        @Valid @RequestBody request: UpdateUserRequest
    ): ApiResponse<UserDto> {
        val user = userService.updateUser(userId, request)
        return ApiResponse.success(user, "更新成功")
    }
    
    @PutMapping("/me/password")
    fun changePassword(
        @AuthenticationPrincipal userId: String,
        @Valid @RequestBody request: ChangePasswordRequest
    ): ApiResponse<Unit> {
        userService.changePassword(userId, request)
        return ApiResponse.success(Unit, "密码修改成功")
    }
    
    @PutMapping("/me/status")
    fun updateStatus(
        @AuthenticationPrincipal userId: String,
        @Valid @RequestBody request: UpdateStatusRequest
    ): ApiResponse<Unit> {
        userService.updateStatus(userId, request.status)
        return ApiResponse.success(Unit, "状态更新成功")
    }
    
    @GetMapping("/active")
    fun getActiveUsers(): ApiResponse<List<UserDto>> {
        val users = userService.getActiveUsers()
        return ApiResponse.success(users)
    }
}
